const translate = require('google-translate-api-zic')
const Koa = require('koa')
const comd = require('commander')
const bodyparser = require('koa-bodyparser')
const HttpsAgent = require('https-proxy-agent')
// const HttpAgent = require('http-proxy-agent')

const logger = require('./logger')

comd.usage('--proxy [localhost:1080]')
    .option('-p, --proxy <proxy>', 'a proxy url')
    .parse(process.argv)

let agent = null
if (comd.proxy) {
    agent = new HttpsAgent(comd.proxy)
}

const app = new Koa()
app.use(bodyparser({
    onerror (err, ctx) {
        ctx.throw(`body parse error:${err}`, 422)
    },
}))

app.use(async (ctx) => {
    if (ctx.request.method !== 'POST') {
        ctx.throw(401, 'method must be POST')
        return
    }

    const { texts, to } = ctx.request.body
    try {
        if (Array.isArray(texts)) {
            ctx.body = await Promise.all(texts.map(async (text) => {
                const tresp = await translate(text, { to, agent: agent || false })
                return tresp.text
            }))
        } else {
            const tresp = await translate(texts, { to, agent: agent || false })
            ctx.body = tresp.text
        }
    } catch (err) {
        logger.error('translate fail', { err, reqbody: JSON.stringify(texts) })
        ctx.throw(500, 'translate fail')
    }
})

app.listen(5001)
